package com.itheima.redbaby.activity;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.TextureView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.redbaby.BaseActivity;
import com.itheima.redbaby.GloableParams;
import com.itheima.redbaby.R;
import com.itheima.redbaby.activity.CartModifyActivity.Myadapter.HoldView;
import com.itheima.redbaby.bean.CartItem;
import com.itheima.redbaby.bean.CartProduct;
import com.itheima.redbaby.bean.ProductProperty;
import com.itheima.redbaby.dao.CartDao;
import com.itheima.redbaby.dao.domain.CartTable;
import com.itheima.redbaby.dao.impl.CartDaoImpl;
import com.itheima.redbaby.engine.impl.CartEngineImpl;
import com.itheima.redbaby.factory.DaoAndEngineFactory;
import com.itheima.redbaby.utils.ImageUtil;
import com.itheima.redbaby.utils.PromptManager;
import com.itheima.redbaby.utils.StreamToString;


public class CartActivity extends BaseActivity  implements OnClickListener {
	private ListView cartProduct_listview;
	//数量总计
	private TextView shopcar_total_buycount_text_1;
	//赠送积分累计
	private TextView shopcar_total_bonus_text_1;
	//金额总计
	private TextView shopcar_total_money_text_1;
	//商品颜色
	private TextView shopcar_item_prodColor_key;
	private TextView shopcar_item_prodColor_text;
	//商品大小
	private TextView shopcar_item_prodSize_key;
	private TextView shopcar_item_prodSize_text;
	//编辑
	private TextView shopcar_update_text;
	//去结算
	private TextView shopcar_toPay_text;
	//继续购物
	private TextView shopcar_gotobuy_text_continue;
	//商品id和商品数量
	private int product_id;
	private int num ;
	//private List<CartItem> cartitemlist;
	private MyAdapter adapter;
	
	private Intent intent;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		init();
	}
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		GloableParams.isBottomEnter=false;
	}
	private void init(){
		setContentView(R.layout.shorpping_cart_pro_activity);
		cartProduct_listview=(ListView) findViewById(R.id.cartProduct_listview);
		shopcar_total_buycount_text_1=(TextView) findViewById(R.id.shopcar_total_buycount_text_1);
		shopcar_total_bonus_text_1=(TextView) findViewById(R.id.shopcar_total_bonus_text_1);
		shopcar_total_money_text_1=(TextView) findViewById(R.id.shopcar_total_money_text_1);
		shopcar_update_text=(TextView) findViewById(R.id.shopcar_update_text);
		shopcar_toPay_text=(TextView) findViewById(R.id.shopcar_toPay_text);
		shopcar_gotobuy_text_continue=(TextView) findViewById(R.id.shopcar_gotobuy_text_continue);
		
		//cartitemlist=new ArrayList<CartItem>();
		//获取上个页面传递数据
		Intent intent = getIntent();
		
		product_id = intent.getIntExtra("product_id",0);
		num = intent.getIntExtra("num", 0);
		
		//为结算、编辑按钮添加click事件监听
		shopcar_toPay_text.setOnClickListener(this);
		shopcar_update_text.setOnClickListener(this);
		shopcar_gotobuy_text_continue.setOnClickListener(this);
		
		//给listview加载数据
		if(GloableParams.isProductCatergery){
			getJsondataToMap();
			GloableParams.isProductCatergery=false;
		}else{
			adapter=new MyAdapter();
			cartProduct_listview.setAdapter(adapter);
			shopcar_total_buycount_text_1.setText(GloableParams.cartMap.get("totalCount")+"");
			shopcar_total_bonus_text_1.setText(GloableParams.cartMap.get("totalPoint")+"");
			shopcar_total_money_text_1.setText(GloableParams.cartMap.get("totalPrice")+"");
		}
		
	}
	
	Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			adapter=new MyAdapter();
			cartProduct_listview.setAdapter(adapter);
			
		};
	};
	/**
	 * 请求数据，根据id得到商品的信息
	 */
	protected void getJsondataToMap() {
		new MyHttpTask() {
			
			protected void onPreExecute() {
				PromptManager.showProgressDialog(CartActivity.this);
			};
			@Override
			protected Object doInBackground(Void... params) {
				CartEngineImpl cartEngineImpl=new CartEngineImpl();
				//JSONObject cartJson=cartEngineImpl.getCartJson();
				cartEngineImpl.getCartJson(product_id,num);
				return null;
			}
			//加载数据后显示总计的数据
			protected void onPostExecute(Object result) {
				PromptManager.closeProgressDialog();
				handler.sendEmptyMessage(0);
				//给购物车总计添加数据
				shopcar_total_buycount_text_1.setText(GloableParams.cartMap.get("totalCount")+"");
				shopcar_total_bonus_text_1.setText(GloableParams.cartMap.get("totalPoint")+"");
				shopcar_total_money_text_1.setText(GloableParams.cartMap.get("totalPrice")+"");
				showCartNumber();
			};
		}.executeHttp();
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.shopcar_toPay_text:
			System.out.println(product_id+":"+num);
			if(GloableParams.isLogin){
				intent=new Intent(CartActivity.this,SummaryPaymentActivity.class);
				startActivity(intent);
				finish();
			}else{
				intent=new Intent(CartActivity.this,LoginActivity.class);
				startActivity(intent);
			}
			break;
			
		case R.id.shopcar_update_text:
			GloableParams.iscartactivity=true;
			intent=new Intent(CartActivity.this,CartModifyActivity.class);
			startActivityForResult(intent, 100);
			break;
		case R.id.shopcar_gotobuy_text_continue:
			intent=new Intent(CartActivity.this,HomeActivity.class);
			startActivity(intent);
			finish();
			break;
		}
		
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==100 && resultCode==Activity.RESULT_OK){
			//总计遂数据变动
			if(GloableParams.cartMap.size()!=0&& GloableParams.cartitemlist.size()!=0){
				int totalnum=0;
				float totalprice=0;
				float totalscore=0;
				
				for(int i=0;i<GloableParams.cartitemlist.size();i++){
					float price = GloableParams.cartitemlist.get(i).getProduct().getPrice();
					int productprom = GloableParams.cartitemlist.get(i).getProductprom();
					float score = GloableParams.cartitemlist.get(i).getProduct().getScore();
					
					totalnum+=productprom;
					totalprice+=price*productprom;
					totalscore+=score;
				}
				shopcar_total_buycount_text_1.setText(totalnum+"");
				shopcar_total_bonus_text_1.setText(totalscore+"");
				shopcar_total_money_text_1.setText(totalprice+"");
				
			}else{
				shopcar_total_buycount_text_1.setText(0+"");
				shopcar_total_bonus_text_1.setText(0+"");
				shopcar_total_money_text_1.setText(0+"");
			}
			adapter.notifyDataSetChanged();
		}
	}
	class MyAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			//List<CartItem> cartitemlist=(List<CartItem>) GloableParams.cartMap.get("cartitemlist");
			
				return GloableParams.cartitemlist.size();
			
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			System.out.println("getview");
			
			
			HoldView holder; 
			
			View v=View.inflate(getApplicationContext(), R.layout.shopping_car_listitem, null);
				holder=new HoldView();
				
				//holder.id=(TextView) v.findViewById(R.id.shopcar_item_prodId_text);
				holder.picpath= (ImageView) v.findViewById(R.id.shopcar_item_prodImage_img);
				holder.name=(TextView) v.findViewById(R.id.shopcar_item_prodName_text);
				holder.colorkey=(TextView) v.findViewById(R.id.shopcar_item_prodColor_key);
				holder.colorvalue=(TextView) v.findViewById(R.id.shopcar_item_prodColor_text);
				holder.sizekey=(TextView) v.findViewById(R.id.shopcar_item_prodSize_key);
				holder.sizevalue=(TextView) v.findViewById(R.id.shopcar_item_prodSize_text);
				holder.price=(TextView) v.findViewById(R.id.shopcar_item_prodPrice_text);
				holder.subtal=(TextView) v.findViewById(R.id.shopcar_item_subtotal_text);
				holder.num=(TextView)v.findViewById(R.id.shopcar_item_num_text);
				v.setTag(holder);
				
				CartItem cartItem = GloableParams.cartitemlist.get(position);
				CartProduct product = cartItem.getProduct();
				List<ProductProperty> productPropertyList = product.getProductPropertyList();
				int productprom = cartItem.getProductprom();
				
				//设置显示信息
				//holder.id.setText(product.getProduct_id());
				holder.name.setText(product.getName());
				holder.colorkey.setText(productPropertyList.get(0).getPkey());
				holder.colorvalue.setText(productPropertyList.get(0).getValue());
				holder.sizekey.setText(productPropertyList.get(1).getPkey());
				holder.sizevalue.setText(productPropertyList.get(1).getValue());
				holder.price.setText(product.getPrice()+"");
				//System.out.println("商品数量======"+GloableParams.cartitemlist.get(position).getProductprom());
				holder.subtal.setText(product.getPrice()*productprom+"");
				holder.num.setText(productprom+"");
				ImageUtil.loadImageFromUrl(holder.picpath, product.getPicpath());
			
			return v;
		}
		class HoldView{
			TextView id;
			TextView name;
			TextView price;
			TextView subtal;
			TextView num;
			TextView colorkey;
			TextView colorvalue;
			TextView	sizekey;
			TextView  sizevalue;
			ImageView picpath;
		}
	}
	
}
